var layer = layui.layer //弹层
    ,table = layui.table //表格
    form = layui.form,
        $ = layui.jquery,
        laydate = layui.laydate,
        code=getQueryVariable("code");

    laydate.render({
        elem: "#cdate"
    });

lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});
function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}
function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}

//select over
(function () {
    let operationList = getCurrentDepartmentUser();
    if(operationList && operationList.list){
        let operationTree = getAllJson(operationList.list);
        getxmselect("#operationCode","operationCode", operationTree)
    }else {
        getxmselect("#operationCode","operationCode", [{name: user.name, value: user.code}])
    }
})()


table.render({
    elem: '#mains'
    ,url:'cost/detail/getCostDetailWarehouseList'
    , where: {
        costCode:code,
    }
    ,toolbar: '#warehousingcostsharingToolbar'
    ,cols: [[
        {field:'costCode', title:'费用编号',sort:true}
        ,{field:'feeCode',hide:true}
        ,{field:'feeName', title:'费用名称',sort:true}
        ,{field:'invoiceCode', title:'出运发票号',sort:true,event:"invoiceCode"}
        ,{field:'stockCode', title:'采购单号',sort:true}
        // ,{field:'registerTime', title:'登记日期',sort:true}//当前时间
        ,{field:'applicationAmount', title:'分摊金额'}//申请金额
        ,{field:'allocationType', title:'分摊类型',sort:true, templet: '#splitTypeSelect'}
        ,{field:'createTimeStr', title:'创建时间',sort:true}//费用创建时间
        ,{field:'tempId',hide:true,sort:true}
        ,{field:'costDetailId',hide:true,sort:true}

    ]]
    ,id: 'mainstableid'
    ,height: 450
    ,done: function (res, curr, count) {
        $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
        $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')

        let initData=[];
        for (let i in res.data){
            for (let j in res.data[i].productInfoVoList) {
                initData.push(res.data[i].productInfoVoList[j]);
            }


        }

        table.render({
            elem: '#childinformation'
            ,data:initData
            // url:'cost/detail/getPlanInStoreInfoList'
            ,cols: [[
                {field: 'billNo',  title: '入库单号',sort:true},
                {field: 'timeStr',  title: '入库日期',sort:true},
                {field: 'warehouseName',  title: '仓库名称',sort:true},
                {field: 'shareCostPrice',  title: '分摊费用单价',sort:true, edit: 'text'},
                {field: 'carryDetailNo',  title: '出运发票号码',sort:true},
                {field: 'lotNo',  title: '批次',sort:true},
                {field: 'productCode',  title: '产品编码',sort:true},
                {field: 'num', title: '数量',sort:true},
                {field: 'volume', title: '体积', sort:true},
                {field: 'netWeight', title: '净重', sort:true},
                {field: 'grossWeight', title: '毛重', sort:true},
                {field: 'person', title: '入库人', sort:true},
                {field: 'operation', title: '操作人', sort:true},
                {field:'tempId',hide:true,sort:true}
                ,{field:'planInStoreProductId',hide:true,sort:true}
                ,{field:'feeCode',hide:true}
            ]]
            ,id: 'childinformationtableid'
            ,page: true
            ,height: 450
        });
    }
});
form.on("select(splittypeselect_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["moaidetailtableid"];
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["splittype"] = data.value;
        }
    });
});

//点击事件
table.on('tool(mainstable)', function(obj){
    let data = obj.data;
    if(obj.event === 'invoiceCode') {
        table.reload('childinformationtableid', {
            url:'cost/detail/getPlanInStoreInfoList',
            where: {
                    invoiceCode:obj.data.invoiceCode,
                    costCode:obj.data.costCode
                }
    }, 'data');
    }
});


//工具栏监听事件
form.on('radio(allocationType)', function(obj){
    let tabledata = table.cache["mainstableid"];



    let childrenTableData = table.cache["childinformationtableid"];
    //体积
    let allVolume=0;
    //数量
    let allNum=0;
    //净重
    let allNetWeight=0;
    //毛重
    let allGrossWeight=0;

    $.each(childrenTableData,function (index,value) {
        let volume=new BigNumber(childrenTableData[index].volume);
        let num=new BigNumber(childrenTableData[index].num);
        let netWeight=new BigNumber(childrenTableData[index].netWeight);
        let grossWeight=new BigNumber(childrenTableData[index].grossWeight);

        allVolume= new BigNumber(allVolume).plus(volume);

        allNum= new BigNumber(allNum).plus(num);

        allNetWeight= new BigNumber(allNetWeight).plus(netWeight);

        allGrossWeight= new BigNumber(allNetWeight).plus(grossWeight);
    });


    $.each(tabledata,function(index,value){
        $("#splitType_"+tabledata[index].tempId).val(obj.value);
        $.each(tabledata,function (index,value) {
            tabledata[index]['allocationType']=obj.value
        })
    });

    form.render();



    $.each(tabledata,function(index,value){
        //分摊总金额
        let applicationAmount=new BigNumber(tabledata[index].applicationAmount);

        $.each(childrenTableData,function (index2,value2) {
            //单个体积
            let onlyVolume=new BigNumber(childrenTableData[index2].volume);
            //单个数量
            let onlyNum=new BigNumber(childrenTableData[index2].num);
            //单个毛重
            let onlyGrossWeight=new BigNumber(childrenTableData[index2].grossWeight);
            //单个净重
            let onlyNetWeight=new BigNumber(childrenTableData[index2].netWeight);

            if (tabledata[index].invoiceCode===childrenTableData[index2].carryDetailNo) {
                //分摊类型
                let allocationType = tabledata[index].allocationType;

                childrenTableData[index2]["costCode"] = tabledata[index].costCode;
                childrenTableData[index2]["costDetailId"] = tabledata[index].costDetailId;
                childrenTableData[index2]["allocationType"]=tabledata[index].allocationType;


                childrenTableData[index2]["shareCostPrice"] = 0;


                switch (allocationType) {
                    case "1"://数量
                        childrenTableData[index2]["shareCostPrice"] = ((applicationAmount.multipliedBy(onlyNum.dividedBy(allNum))).dividedBy(onlyNum)).toFixed(4);
                        break;
                    case "2"://体积
                        childrenTableData[index2]["shareCostPrice"] = ((applicationAmount.multipliedBy(onlyVolume.dividedBy(allVolume))).dividedBy(onlyNum)).toFixed(4);
                        break;
                    case "3"://净重
                        childrenTableData[index2]["shareCostPrice"] = ((applicationAmount.multipliedBy(onlyNetWeight.dividedBy(allNetWeight))).dividedBy(onlyNum)).toFixed(4);
                        break;
                    case "4"://毛重
                        childrenTableData[index2]["shareCostPrice"] = ((applicationAmount.multipliedBy(onlyGrossWeight.dividedBy(allGrossWeight))).dividedBy(onlyNum)).toFixed(4);
                        break;
                    default:
                        childrenTableData[index2]["shareCostPrice"] = 0;
                }
            }
        });

    });
    table.reload('childinformationtableid',{ data:childrenTableData });
});

form.on('submit(submitform)', function(data){
    table.reload('mainstableid', {
        where: data.field
    }, 'data');
    return false;
});
// table.on('edit(mainstable)',function (obj) {
//     var old=$(this).prev().text();//旧值
//     //判断数据类型 ,,,,,,,
//     if((obj.field== "contributions")&&!isNumber(obj.value)) {
//         layer.msg('请输入数字');
//         $(this).val(old);
//         return;
//     }
// });
//监听下拉框
form.on("select(splitTypeSelect_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["mainstableid"];
    let childrenTableData = table.cache["childinformationtableid"];
    //体积
    let allVolume=0;
    //数量
    let allNum=0;
    //净重
    let allNetWeight=0;
    //毛重
    let allGrossWeight=0;

    $.each(childrenTableData,function (index,value) {
        let volume=new BigNumber(childrenTableData[index].volume);
        let num=new BigNumber(childrenTableData[index].num);
        let netWeight=new BigNumber(childrenTableData[index].netWeight);
        let grossWeight=new BigNumber(childrenTableData[index].grossWeight);

        allVolume= new BigNumber(allVolume).plus(volume);

        allNum= new BigNumber(allNum).plus(num);

        allNetWeight= new BigNumber(allNetWeight).plus(netWeight);

        allGrossWeight= new BigNumber(allNetWeight).plus(grossWeight);
    });

    $.each(tabledata,function(index,value){
        //分摊金额
        let applicationAmount=new BigNumber(tabledata[index].applicationAmount);

        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["allocationType"] = data.value;

            $.each(childrenTableData,function (index2,value2) {
                //单个体积
                let onlyVolume=new BigNumber(childrenTableData[index2].volume);
                //单个数量
                let onlyNum=new BigNumber(childrenTableData[index2].num);
                //单个毛重
                let onlyGrossWeight=new BigNumber(childrenTableData[index2].grossWeight);
                //单个净重
                let onlyNetWeight=new BigNumber(childrenTableData[index2].netWeight);

                if (tabledata[index].invoiceCode===childrenTableData[index2].carryDetailNo){
                    //分摊类型
                    let allocationType=tabledata[index].allocationType;

                    childrenTableData[index2]["costCode"]=tabledata[index].costCode;
                    childrenTableData[index2]["costDetailId"]=tabledata[index].costDetailId;
                    childrenTableData[index2]["allocationType"]=tabledata[index].allocationType;



                    childrenTableData[index2]["shareCostPrice"]=0;

                    switch (allocationType) {
                        case "1"://数量

                            childrenTableData[index2]["shareCostPrice"]=((applicationAmount.multipliedBy(onlyNum.dividedBy(allNum))).dividedBy(onlyNum)).toFixed(4);

                            break;
                        case "2"://体积
                            let aa=onlyVolume.dividedBy(allVolume);
                            let bb=applicationAmount.multipliedBy(aa);
                            let cc=bb.dividedBy(onlyNum).toFixed(4);
                            childrenTableData[index2]["shareCostPrice"]=cc;

                            break;
                        case "3"://净重
                            childrenTableData[index2]["shareCostPrice"]=((applicationAmount.multipliedBy(onlyNetWeight.dividedBy(allNetWeight))).dividedBy(onlyNum)).toFixed(4);

                            break;
                        case "4"://毛重
                            childrenTableData[index2]["shareCostPrice"]=((applicationAmount.multipliedBy(onlyGrossWeight.dividedBy(allGrossWeight))).dividedBy(onlyNum)).toFixed(4);

                            break;
                        default:
                            childrenTableData[index2]["shareCostPrice"]=0;
                    }
                }

            })
        }
    });

    table.reload('childinformationtableid',{ data:childrenTableData });
});

//监听提交
$("#save").on("click",function () {
    let req = table.cache["childinformationtableid"];
    if (req.length===0){
        layer.msg("费用可能已被分摊");
        return false;
    }
    let indexsl=0;
    $.each(req,function(index,value){
        if(typeof (req[index]["shareCostPrice"])== "undefined" || req[index]["shareCostPrice"]=="" || req[index]["shareCostPrice"]==0){
            layer.msg("请选择分摊类型");
            indexsl++;
            return false;
        }
    });
    if(indexsl == 0){
        $.ajax({
            type : 'POST',
            url:'costApportionment/addCostApportionment',
            data:JSON.stringify(req),
            dataType:"json",
            contentType: 'application/json',
            success : function (data) {
                layer.msg("保存成功", {icon: 6});
                setTimeout(function () {
                    //保存成功则关闭此页面
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                },1000)
            }
        });

    }
    return false;
});

$("#shutdown").on("click",function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
});

function isNumber(val) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}